const query=require('../db/mysql')
const {success,error}=require('../model/model')
const {md5}=require('utility')
const jwt=require('jsonwebtoken')
class CarController{
    register=async(ctx)=>{
        const {username,password,nickname}=ctx.request.body
        const isHaveSql=`select * from users where username="${username}"`
        const isHave=await query(isHaveSql)
        if(isHave.length){
            ctx.body=error('账号已存在')
            return
        }
        const sql=`insert into users(username,password,nickname) values("${username}","${md5(String(password))}","${nickname}")`
        const data=await query(sql)
        if(data.affectedRows===1){
            ctx.body=success('注册成功')
        }else{
            ctx.body=error('注册失败')
        }
    }
    login=async(ctx)=>{
        const {username,password}=ctx.request.body
        const isHaveSql=`select * from users where username="${username}" and password="${md5(String(password))}"`
        const isHave=await query(isHaveSql)

        if(isHave.length){
            ctx.body=success({
                data:isHave[0],
                token:jwt.sign({id:isHave[0].id},'1812a')
            },'登录成功')
        }else{
            ctx.body=error('登录失败')
        }
    }
}
module.exports=new CarController()